package com.ben.xinyue.seckill.controller;

import com.ben.xinyue.seckill.domain.entity.MiaoshaOrder;
import com.ben.xinyue.seckill.domain.entity.MiaoshaUser;
import com.ben.xinyue.seckill.domain.entity.OrderInfo;
import com.ben.xinyue.seckill.domain.vo.GoodsVo;
import com.ben.xinyue.seckill.service.GoodsService;
import com.ben.xinyue.seckill.service.MiaoshaOrderService;
import com.ben.xinyue.seckill.service.OrderInfoService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: RedirectController
 * @Description: 跳转页面
 * @author: xinyue
 * @date: 2020/9/2 9:17 下午
 * @version: 1.0.0
 */
@RequestMapping("/redirect")
@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RedirectController {

    private final GoodsService goodsService;
    private final RedissonClient redissonClient;
    private final ThymeleafViewResolver thymeleafViewResolver;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/goods/list", produces = "text/html")
    @ResponseBody
    public String goodsList(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user){
        Object html = redissonClient.getBucket("goodsList").get();
        if(Objects.nonNull(html)){
            return html.toString();
        }
        List<GoodsVo> goodsVoList = goodsService.listGoodsVo();
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsVoList);
        WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        String h = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        if(!StringUtils.isEmpty(h)){
            redissonClient.getBucket("goodsList").set(h,1, TimeUnit.MINUTES);
        }
        return h;
    }


}
